<?php
/**
 * 微信红包(商户下发红包给用户)
 */

class WxRedPackAction extends Action
{
    /**
     * @api {Post} WxRedPack/sendRedPack 01、发送微信红包
     * @apiGroup WxRedPack
     * @apiVersion 1.0.0
     * @apiDescription  发送微信红包<br />
     * @apiParam (输入参数：) {String}        sessionId 登录sessionId
     * @apiParam (返回参数：) {object}         array 错误结果集
     * @apiParam (返回参数：) {string}         array.error 返回错误码
     * @apiParam (返回参数：) {string}         array.message 返回错误消息
     */
    public function sendRedPack()
    {
        echo '成功!';exit();
        $sn =   I('get.sn');
        log::write('日志$sn '.print_r($sn,1));
        $result =   M('security_code')->where(array('code'=>array('eq',$sn)))->find();
        
        if($result){
            if($result['issued'] == '0'){
                
                //导入微信基类
                require_once APP_PATH . 'Org/wxpayapi/lib/WxPay.Api.php';
                require_once APP_PATH . 'Org/wxpayapi/lib/WxPay.JsApiPay.php';
                
                // 获取用户openid
                $tools  = new JsApiPay();
                $openId = $tools->GetOpenidd();
                
                log::write('日志'.print_r($openId,1));
                if($openId){
                    $reMap['supplier_idx']  =   $result['supplier_idx'];
                    $reMap['activity_idx']  =   $result['activity_idx'];
                    $reInfo =   M('activity_reward')->where($reMap)->find();
                    if($reInfo['price']){
                        //创建记录
                        $order_idx  =   doOrderSn(22);
                        $data['order_idx']  =   $order_idx;
                        $data['openid'] =   $openId;
                        $data['create_time'] =   time();
                        $data['code'] =   $sn;
                        $data['status'] =   1;
                        $data['price'] =   $reInfo['price'];
                        $data['supplier_idx'] =   $result['supplier_idx'];
                        $data['activity_idx'] =   $result['activity_idx'];
                        $data['goods_idx'] =   $result['goods_idx'];
                        $data['edit_time'] =   time();
                        $rePhy  =   M('code_phy')->data($data)->add();
                        if($rePhy){
                            //发送红包
                            $sendRed = $this->sendRedPackOperated($order_idx, $openId, $reInfo['price'], getSupplierName($result['supplier_idx']));
                            
                            if ($sendRed === true) {
                                $cdata['is_handle']  =   1;
                                $cdata['handle_time']  =   time();
                                $cdata['issued']  =   1;
                                M('security_code')->where(array('code'=>array('eq',$sn)))->data($data)->save();
                                $msg    =   '红包发放成功';
                            } else {
                                $sendMap['order_idx']    =   array('eq',$order_idx);
                                $phyDate['status']    =   0;
                                $phyDate['edit_time']    =   time();
                                M('code_phy')->where($sendMap)->data($phyDate)->save();
                                
                                if ($sendRed == 'fail_01') {
                                    $msg    =   '请求可能存在风险，请使用常用微信号';
                                } elseif ($sendRed == 'fail_02') {
                                    $msg    =   '您今天的领取已经达到上限';
                                } else {
                                    $msg    =   '奖品发送失败';
                                }
                            }
                            
                        } else {
                            $msg    =   '创建发送请求失败';
                        }
                    } else {
                        $msg    =   '活动异常，请联系管理员';
                    }
                    
                } else {
                    $msg    =   '微信授权获取失败';
                }
            } else {
                $msg    =    '已经领取';
            }
        } else {
            $msg    =    '没有查到这个卡券';
        }
        $this->assign('msg',$msg);
        $this->display('wx/index');

        
    }


    // 发送微信红包
    private function sendRedPackOperated($orderNo, $openid, $amount, $supplierName)
    {
        //导入微信基类
        require_once APP_PATH . 'Org/wxpayapi/lib/WxPay.Api.php';
        require_once APP_PATH . 'Org/wxpayapi/lib/WxPay.JsApiPay.php';

        // 配置接口需要参数
        $inputObj = new WxRedPackToOpenid();
        $inputObj->SetNonce_str(WxPayApi::getNonceStr()); // 随机字符串
        $inputObj->SetWxAppid(WxPayConfig::APPID); // 公众账号ID
        $inputObj->SetMch_id(WxPayConfig::MCHID); // 商户号
        $inputObj->SetMch_billno($orderNo); // 商户订单号
        $inputObj->SetSend_name($supplierName); // 商户名称
        $inputObj->SetRe_openid($openid); // 接受红包的用户openid
        $inputObj->SetTotal_amount($amount * 100); // 红包金额，单位分
        $inputObj->SetTotal_num(); // 红包个数，默认1个
        $inputObj->SetWishing('感谢您参与！'); // 红包祝福语
        $inputObj->SetClient_ip($_SERVER['REMOTE_ADDR']); // 调用接口的服务器Ip地址
        $inputObj->SetAct_name('幸运抽奖'); // 活动名称
        $inputObj->SetRemark('参与多多，惊喜多多！'); // 备注
        $inputObj->SetScene_id('PRODUCT_2'); // 场景_抽奖
        $inputObj->SetSign(); // 签名

        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        $xml = $inputObj->ToXml();
        log::write("发送红包请求参数：" . $xml);
        $response = $this->postXmlCurl($xml, $url, true);
        log::write("发送红包返回结果XML：" . $response);
        if ($response) {
            $result = WxPayResults::Init($response);
            log::write("发送红包处理后返回结果：" . $result);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                return true;
            }

            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'FAIL') {
                if ($result['err_code'] == 'PROCESSING') {
                    return true;
                } elseif ($result['err_code'] == 'NO_AUTH') {
                    return 'fail_01';
                } elseif ($result['err_code'] == 'SENDNUM_LIMIT') {
                    return 'fail_02';
                }
            }
        }

        return false;
    }


    private function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        //如果有配置代理这里就设置代理
        if (WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
            && WxPayConfig::CURL_PROXY_PORT != 0) {
            curl_setopt($ch, CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
            curl_setopt($ch, CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, false);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($useCert == true) {
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT,APP_PATH . 'Org/wxpayapi/zcerts/apiclient_cert.pem');
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, APP_PATH . 'Org/wxpayapi/zcerts/apiclient_key.pem');
//             curl_setopt($ch, CURLOPT_CAINFO, WxPayConfig::SSLROOTCA_PATH);
            
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            log::write("请求微信发送红包crul报错，错误码：" . $error);
            // throw new WxPayException("curl出错，错误码:$error");
            return true;exit;
            return false;
        }
    }
    

    public function https_post_curl($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
    
        return $output;
    }
}
